package cn.com.xiaoshoujia.wallet.activity;

import cn.com.xiaoshoujia.activities.exception.ActivityException;
import cn.com.xiaoshoujia.application.service.WalletService;
import cn.com.xiaoshoujia.constants.Scene;
import cn.com.xiaoshoujia.domain.dto.FundsPoolTransactionDetailsDTO;
import cn.com.xiaoshoujia.domain.dto.SettlementDTO;
import cn.com.xiaoshoujia.domain.dto.WalletLogsDTO;
import cn.com.xiaoshoujia.domain.dto.WalletTransactionDetailsDTO;
import cn.com.xiaoshoujia.infrastructure.utils.Result;
import cn.com.xiaoshoujia.wallet.entity.ErrorLogs;
import cn.com.xiaoshoujia.wallet.entity.SettlementError;
import cn.com.xiaoshoujia.wallet.entity.WxpayMsg;
import cn.com.xiaoshoujia.wallet.mapper.ErrorLogsMapper;
import cn.com.xiaoshoujia.wallet.mapper.SettlementErrorMapper;
import cn.com.xiaoshoujia.wallet.mapper.WxpayMsgMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Repository
public class WalletActivity {

    private Logger logger = LoggerFactory.getLogger(WalletActivity.class);

    @Autowired
    ErrorLogsMapper errorLogsMapper;

    @Autowired
    WalletService walletService;

    @Autowired
    WxpayMsgMapper wxpayMsgMapper;

    @Autowired
    SettlementErrorMapper settlementErrorMapper;

    /**
     * @Author: yangrui
     * @Description: 查询钱包服务错误日志，迁移到钱包服务日志表，并更改错误日志状态为已删除
     * @Date: 下午3:20 2017/9/5
     */
    @Transactional
    public boolean transfer() {
        int i = 0;
        //获取错误日志
        List<ErrorLogs> errorLogsList = errorLogsMapper.findAll();
        if (errorLogsList != null && errorLogsList.size() > 0) {
            for (ErrorLogs errorLogs : errorLogsList) {
                //根据orderID获取相关钱包记录
                List<WalletLogsDTO> walletLogsList = walletService.findWalletLogsByOrderId(errorLogs.getOrderId());
                //若压根儿没有钱包日志，就直接保存
                if (walletLogsList == null || walletLogsList.size() == 0) {
                    WalletLogsDTO walletLogsDTO = new WalletLogsDTO();
                    BeanUtils.copyProperties(errorLogs, walletLogsDTO);
                    Result result = walletService.saveWalletLogs(walletLogsDTO);
                    if ("SUCCESS".equals(result.getCode())) {
                        i = errorLogsMapper.updateStatus(errorLogs.getId());
                    }
                    if (i == 0) {
                        logger.error("系统异常");
                        throw new ActivityException("系统异常");
                    }
                } else {
                    //循环找出需要恢复的日志
                    for (WalletLogsDTO logsDTO : walletLogsList){
                        //开始比较 error日志 和 已经存在的钱包日志 ， 是否是一样的记录
                        // 如果是一样的记录就更新error日志的状态为已处理，否则就尝试恢复
                        ErrorLogs comparative = new ErrorLogs();
                        BeanUtils.copyProperties(logsDTO, comparative);
                        //如果已经存在钱包记录，就更新状态
                        if (errorLogs.equals(comparative)){
                            i = errorLogsMapper.updateStatus(errorLogs.getId());
                        }else {
                            //如果不存在钱包记录，就保存
                            WalletLogsDTO walletLogsDTO = new WalletLogsDTO();
                            BeanUtils.copyProperties(errorLogs, walletLogsDTO);
                            Result result = walletService.saveWalletLogs(walletLogsDTO);
                            if ("SUCCESS".equals(result.getCode())) {
                                i = errorLogsMapper.updateStatus(errorLogs.getId());
                            }
                        }
                        if (i == 0) {
                            logger.error("系统异常");
                            throw new ActivityException("系统异常");
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * @Author: yangrui
     * @Description: 保存微信支付回调信息
     * @Date: 下午5:16 2017/9/5
     */
    public boolean saveWxpayMsg(WxpayMsg wxpayMsg) {
        return wxpayMsgMapper.save(wxpayMsg) > 0;
    }

    /**
     * @Author: yangrui
     * @Description: 下单异常处理
     * @Date: 下午6:04 2017/9/5
     */
    @Transactional
    public boolean responseMsg() {
        int i = 0;
        List<WxpayMsg> wxpayMsgList = wxpayMsgMapper.findAll();
        if (wxpayMsgList != null && wxpayMsgList.size() > 0) {
            for (WxpayMsg wxpayMsg : wxpayMsgList) {
                String orderId = wxpayMsg.getOrderId();
                List<WalletLogsDTO> walletLogsList = walletService.findWalletLogsByOrderId(orderId);
                if (walletLogsList != null) {
                    for (WalletLogsDTO walletLogs : walletLogsList) {
                        /*判断交易明细是否统计过该订单*/
                        Result result = walletService.isExistsTransactionDetail(orderId, walletLogs.getType());
                        if ("FAIL".equals(result.getCode())) {
                            logger.debug("交易明细未统计过该订单");
                            Result result1 = null;
                            if (walletLogs.getType() == 0) {
                                WalletTransactionDetailsDTO walletTransactionDetailsDTO = new WalletTransactionDetailsDTO();
                                BeanUtils.copyProperties(walletLogs, walletTransactionDetailsDTO);
                                result1 = walletService.saveWalletTransactionDetails(walletTransactionDetailsDTO);
                            }
                            if (walletLogs.getType() == 1) {
                                FundsPoolTransactionDetailsDTO fundsPoolTransactionDetailsDTO = new FundsPoolTransactionDetailsDTO();
                                BeanUtils.copyProperties(walletLogs, fundsPoolTransactionDetailsDTO);
                                result1 = walletService.saveFundsPoolTransactionDetails(fundsPoolTransactionDetailsDTO);
                            }
                            logger.debug("保存钱包流水 {}", result1.getCode());
                            if ("SUCCESS".equals(result1.getCode())) {
                                i = wxpayMsgMapper.updateStatus(wxpayMsg.getId());
                            }
                        } else {
                            i = wxpayMsgMapper.updateStatus(wxpayMsg.getId());
                        }
                        if (i == 0) {
                            logger.error("系统异常");
                            throw new ActivityException("系统异常");
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * @Author: yangrui
     * @Description: 保存钱包服务结算异常信息保存
     * @Date: 下午3:08 2017/9/6
     */
    public boolean settlementError(SettlementError settlementError) {
        return settlementErrorMapper.save(settlementError) > 0;
    }

    /**
     * @Author: yangrui
     * @Description: 保存钱包服务结算处理
     * @Date: 下午3:31 2017/9/6
     */
    @Transactional
    public boolean settlement() {
        logger.debug("异常结算开始");
        int i = 0;
        List<String> fkCompanyXcodelist = settlementErrorMapper.findFkCompanyXcode();
        if (fkCompanyXcodelist != null && fkCompanyXcodelist.size() > 0) {
            for (String fkCompanyXcode : fkCompanyXcodelist) {
                logger.debug("待结算企业xcode {}", fkCompanyXcode);
                List<SettlementError> settlementErrorList = settlementErrorMapper.findByFkCompanyXcode(fkCompanyXcode);
                if (settlementErrorList != null && settlementErrorList.size() > 0) {
                    List<String> orderList = new ArrayList<String>();
                    settlementErrorList.stream().forEach(object -> {
                        SettlementError settlementError = (SettlementError) object;
                        logger.debug("异常结算orderId {}", settlementError.getOrderId());
                        orderList.add(settlementError.getOrderId());
                    });
                    SettlementDTO settlementDTO = new SettlementDTO();
                    settlementDTO.setOpeartor(fkCompanyXcode);
                    settlementDTO.setOpeartorType(0);
                    settlementDTO.setFkCompanyXcode(fkCompanyXcode);
                    settlementDTO.setScene(Scene.TEAM_HEAD_SUCCESS.getCode());
                    settlementDTO.setListOrderId(orderList);
                    try {
                        Result result = walletService.settlement(settlementDTO);
                        logger.debug("异常结算钱包服务处理结果 {}", result);
                        if ("SUCCESS".equals(result.getCode())) {
                            for (SettlementError settlementError : settlementErrorList) {
                                i = settlementErrorMapper.updateStatus(settlementError.getId());
                            }
                        }else{
                            logger.error("异常结算钱包服务处理结果 {}", result);
                        }
                    } catch (Exception e) {
                        logger.error("钱包服务异常");
                    }
                }
            }
        }
        return true;
    }
}